package cn.edu.njnu.opengmpback.collaboration.resource.controller;

import cn.edu.njnu.opengmpback.common.service.GeoServerBoundsService;
import cn.edu.njnu.opengmpback.common.utils.JsonResult;
import cn.edu.njnu.opengmpback.common.utils.ResultUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * GeoServer边界信息代理API控制器
 * 用于解决前端CORS问题，提供后端代理访问GeoServer REST API
 * 
 * @author Claude
 * @date 2024-08-20
 */
@Slf4j
@RestController
@RequestMapping("/api/geoserver")
public class GeoServerBoundsController {

    @Autowired
    private GeoServerBoundsService geoServerBoundsService;

    /**
     * 获取指定图层的地理边界信息
     * 前端调用: /api/geoserver/bounds?workspace=activity_xxx&layer=layerName
     * 
     * @param workspace 工作空间名称
     * @param layer 图层名称
     * @return 包含边界信息的JSON响应
     */
    @GetMapping("/bounds")
    public JsonResult getLayerBounds(
            @RequestParam("workspace") String workspace,
            @RequestParam("layer") String layer) {
        
        log.info("🔍 接收到前端请求获取图层边界: workspace={}, layer={}", workspace, layer);
        
        try {
            // 对中文字符进行解码处理
            String decodedWorkspace = java.net.URLDecoder.decode(workspace, "UTF-8");
            String decodedLayer = java.net.URLDecoder.decode(layer, "UTF-8");
            
            log.info("📝 解码后参数: workspace={}, layer={}", decodedWorkspace, decodedLayer);
            
            // 调用边界服务获取数据
            Map<String, Double> bounds = geoServerBoundsService.getLayerBounds(decodedWorkspace, decodedLayer);
            
            if (bounds != null && !bounds.isEmpty()) {
                log.info("✅ 成功获取图层边界信息: {}", bounds);
                
                // 构造标准化的响应格式
                Map<String, Object> responseData = new HashMap<>();
                responseData.put("minLon", bounds.get("minLon"));
                responseData.put("minLat", bounds.get("minLat"));
                responseData.put("maxLon", bounds.get("maxLon"));
                responseData.put("maxLat", bounds.get("maxLat"));
                responseData.put("workspace", decodedWorkspace);
                responseData.put("layer", decodedLayer);
                
                return ResultUtils.success(responseData);
            } else {
                log.warn("⚠️ 无法获取图层边界信息: workspace={}, layer={}", decodedWorkspace, decodedLayer);
                return ResultUtils.error(-1, "无法获取图层边界信息，可能图层不存在或尚未完全发布");
            }
            
        } catch (Exception e) {
            log.error("❌ 获取图层边界时发生错误", e);
            return ResultUtils.error(-1, "获取图层边界失败: " + e.getMessage());
        }
    }

    /**
     * 获取图层的详细信息（包括数据类型、处理建议等）
     * 
     * @param workspace 工作空间名称  
     * @param layer 图层名称
     * @return 图层详细信息
     */
    @GetMapping("/layer-info")
    public JsonResult getLayerInfo(
            @RequestParam("workspace") String workspace,
            @RequestParam("layer") String layer) {
        
        log.info("🔍 获取图层详细信息: workspace={}, layer={}", workspace, layer);
        
        try {
            String decodedWorkspace = java.net.URLDecoder.decode(workspace, "UTF-8");
            String decodedLayer = java.net.URLDecoder.decode(layer, "UTF-8");
            
            // 获取边界信息
            Map<String, Double> bounds = geoServerBoundsService.getLayerBounds(decodedWorkspace, decodedLayer);
            
            // 获取数据类型信息
            String dataTypeInfo = geoServerBoundsService.getDataTypeInfo(decodedLayer);
            
            Map<String, Object> layerInfo = new HashMap<>();
            layerInfo.put("workspace", decodedWorkspace);
            layerInfo.put("layer", decodedLayer);
            layerInfo.put("bounds", bounds != null ? bounds : new HashMap<>());
            layerInfo.put("dataType", dataTypeInfo);
            layerInfo.put("hasBounds", bounds != null && !bounds.isEmpty());
            
            return ResultUtils.success(layerInfo);
            
        } catch (Exception e) {
            log.error("❌ 获取图层信息失败", e);
            return ResultUtils.error(-1, "获取图层信息失败: " + e.getMessage());
        }
    }

    /**
     * 获取Vec数据的处理建议
     * 
     * @param fileName 文件名
     * @return Vec数据处理建议
     */
    @GetMapping("/vec-advice")
    public JsonResult getVecProcessingAdvice(@RequestParam("fileName") String fileName) {
        log.info("🔍 获取Vec数据处理建议: fileName={}", fileName);
        
        try {
            String decodedFileName = java.net.URLDecoder.decode(fileName, "UTF-8");
            Map<String, String> advice = geoServerBoundsService.getVecProcessingAdvice(decodedFileName);
            
            return ResultUtils.success(advice);
            
        } catch (Exception e) {
            log.error("❌ 获取Vec处理建议失败", e);
            return ResultUtils.error(-1, "获取Vec处理建议失败: " + e.getMessage());
        }
    }

    /**
     * 健康检查接口
     * 
     * @return 服务状态
     */
    @GetMapping("/health")
    public JsonResult healthCheck() {
        Map<String, Object> healthStatus = new HashMap<>();
        healthStatus.put("status", "ok");
        healthStatus.put("service", "GeoServer Bounds API");
        healthStatus.put("timestamp", System.currentTimeMillis());
        return ResultUtils.success(healthStatus);
    }
}